import { DownOutlined, KeyOutlined, LogoutOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import type { MenuProps } from 'antd'
import { Dropdown, Form, Input, message, Modal, Space, Spin } from 'antd'
import React, { useState } from 'react'
import useuserInfoStore from '@/store/userInfo'
import { clearStorage } from '@/utils/storage'
import http from '@/utils/request'
import './index.scss'

interface FieldType {
  username?: string;
  oldPassword?: string;
  newPassword?: string;
  confirmPassword?: string;
}

const items: MenuProps['items'] = [
  {
    label: '修改密码',
    icon: <KeyOutlined />,
    key: 'password'
  },
  {
    label: '退出登录',
    icon: <LogoutOutlined />,
    key: 'logout'
  }
]

export default function Header() {
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const userInfo = useuserInfoStore((state) => state.userInfo)
  const updateUserInfo = useuserInfoStore((state) => state.updateUserInfo)
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  const onClick: MenuProps['onClick'] = ({ key }) => {
    if(key === 'logout') {
      setLoading(true)
      http.get('/disp/manage/system/logout').then(() => {
      }).finally(() => {
        clearStorage()
        updateUserInfo({
          token: '',
          permissionCodes: []
        })
        navigate('/login', { replace: true })
        setLoading(false)
      })
    }
    if(key === 'password') {
      setIsModalOpen(true)
    }
    
    // setUsername(key)
  }

  const handleOk = () => {
    form.validateFields()
      .then(values => {
        http.post('/disp/sys/user/updatePassword', values).then(() => {
          setIsModalOpen(false)
        }).catch(err => {
          message.error(err.msg || '操作失败')
        })
        // 提交表单逻辑
      })
  }
  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const [form] = Form.useForm()

  return (
    <div className="header flex-row flex-item">
      {loading ? <Spin tip="退出中..." fullscreen/> : null}
      <h2 style={{ paddingRight: '20px' }}>派单系统</h2>
      <div className="flex1"/>
      <Dropdown menu={{ items, onClick }}>
        <a onClick={(e) => e.preventDefault()}>
          <Space>
            你好，{userInfo?.username}
            <DownOutlined />
          </Space>
        </a>
      </Dropdown>
      <Modal title="密码修改" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入旧密码' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item<FieldType>
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: '请输入新密码' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item<FieldType>
            label="重复密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              {
                required: true,
                message: '请再次输入新密码'
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的新密码不一致'))
                }
              })
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
